package com.jinzheng.qhnetty.commont.waitnetty;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jinzheng.qhnetty.util.GBT32960Decoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义的Handler需要继承Netty规定好的HandlerAdapter
 **/
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    private List<Object> out = new ArrayList<>();

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获取客户端发送过来的消息
        ByteBuf byteBuf = (ByteBuf) msg;
        GBT32960Decoder gbt32960Decoder = new GBT32960Decoder();
        gbt32960Decoder.decode(ctx,byteBuf,out);
        if(CollectionUtils.isNotEmpty(out)){
            System.out.println(JSONObject.toJSONString(out, SerializerFeature.WriteMapNullValue));
//            KafkaProducer kafkaProducer = SpringUtil.getBean(KafkaProducer.class);
//            kafkaProducer.sendMessageByTopic("tesdsea",null, JSONObject.toJSONString(out, SerializerFeature.WriteMapNullValue));
//            out = new ArrayList<>();
        }
        System.out.println("收到客户端" + ctx.channel().remoteAddress() + "发送的消息：" + byteBuf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //发送消息给客户端
        ctx.writeAndFlush(Unpooled.copiedBuffer("服务端已收到消息，并给你发送一个问号?", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //发生异常，关闭通道
        ctx.close();
    }
}
